<template>
  <div class="container">
    <!-- 左侧菜单 -->
    <t-menu
      theme="light"
      :default-expanded="['group1']"
      v-model:value="activeAnchor"
      @change="handleMenuChange"
      style="width: 240px"
    >
    <t-submenu value="sub1" title="二级菜单">
          <t-menu-item value="section2">配置管理</t-menu-item>
          <t-menu-item value="section3">权限设置</t-menu-item>
        </t-submenu>
        <t-submenu value="sub2" title="二级菜单">
          <t-menu-item value="section4">配置管理</t-menu-item>
          <t-menu-item value="section5">权限设置</t-menu-item>
        </t-submenu>
    </t-menu>

    <!-- 右侧内容 -->
    <div 
      class="content-wrapper"
      ref="scrollContainer"
      @scroll.passive="handleScroll"
    >
      <div 
        v-for="section in sections"
        :id="section.id"
        :key="section.id"
        class="anchor-section"
      >
        <h2>{{ section.title }}</h2>
        <div>{{ section.content }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

const activeAnchor = ref('section1')
const scrollContainer = ref(null)
let observer = null

const sections = ref([
  { id: 'section1', title: '基础信息', content: '...' },
  { id: 'section2', title: '配置管理', content: '...' },
  { id: 'section3', title: '权限设置', content: '...' },
  { id: 'section4', title: '配置管理', content: '...' },
  { id: 'section5', title: '权限设置', content: '...' }
])

// 菜单点击处理‌:ml-citation{ref="8" data="citationList"}
const handleMenuChange = (val) => {
  const target = document.getElementById(val)
  if (target) {
    target.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }
}

// 初始化观察器‌:ml-citation{ref="3,6" data="citationList"}
const initIntersectionObserver = () => {
  const options = {
    root: scrollContainer.value,
    threshold: 0.5,
    rootMargin: '0px'
  }

  observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        activeAnchor.value = entry.target.id
      }
    })
  }, options)

  sections.value.forEach(section => {
    const el = document.getElementById(section.id)
    if (el) observer.observe(el)
  })
}

onMounted(() => {
  initIntersectionObserver()
})

onBeforeUnmount(() => {
  if (observer) observer.disconnect()
})
</script>

<style scoped>
.container {
  display: flex;
  height: 100vh;
}

.content-wrapper {
  flex: 1;
  height: 100%;
  overflow-y: auto;
  padding: 20px;
}

.anchor-section {
  min-height: 600px;
  margin-bottom: 40px;
  padding: 20px;
  border: 1px solid #eee;
}
</style>
